summaryrefslogtreecommitdiff
path: root/app/api/files/[...path]/route.ts
blob: f92dd1d80ab457df806be72d6bfa978dcf265027 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// app/api/files/[...path]/route.ts
import { NextRequest, NextResponse } from 'next/server'
import { readFile } from 'fs/promises'
import { join } from 'path'
import { stat } from 'fs/promises'

export async function GET(
  request: NextRequest,
  { params }: { params: { path: string[] } }
) {
  try {

    const path = request.nextUrl.searchParams.get("path");


    // 경로 파라미터에서 파일 경로 조합
    const filePath = join(process.cwd(), 'uploads', ...params.path)
    
    // 파일 존재 여부 확인
    try {
      await stat(filePath)
    } catch (error) {
      return NextResponse.json(
        { error: 'File not found' },
        { status: 404 }
      )
    }
    
    // 파일 읽기
    const fileBuffer = await readFile(filePath)
    
    // 파일 확장자에 따른 MIME 타입 설정
    const fileName = params.path[params.path.length - 1]
    const fileExtension = fileName.split('.').pop()?.toLowerCase()
    
    let contentType = 'application/octet-stream'
    
    if (fileExtension) {
      const mimeTypes: Record<string, string> = {
        'pdf': 'application/pdf',
        'doc': 'application/msword',
        'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'xls': 'application/vnd.ms-excel',
        'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'ppt': 'application/vnd.ms-powerpoint',
        'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        'txt': 'text/plain',
        'csv': 'text/csv',
        'png': 'image/png',
        'jpg': 'image/jpeg',
        'jpeg': 'image/jpeg',
        'gif': 'image/gif',
      }
      
      contentType = mimeTypes[fileExtension] || contentType
    }
    
    // 다운로드 설정
    const headers = new Headers()
    headers.set('Content-Type', contentType)
    headers.set('Content-Disposition', `attachment; filename="${fileName}"`)
    
    return new NextResponse(fileBuffer, {
      status: 200,
      headers,
    })
  } catch (error) {
    console.error('Error downloading file:', error)
    return NextResponse.json(
      { error: 'Failed to download file' },
      { status: 500 }
    )
  }
}